package edu.guigu.clientserivce;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Random;

import edu.guigu.clientserivce.databinding.ActivityMainBinding;
import edu.guigu.serverservice.remoteaidl.IRemoteAidl;
import edu.guigu.serverservice.remoteaidl.Student;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainBinding binding;
    private Messenger clientMessenager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        clientMessenager = new Messenger(new MessengerHander());

        binding.btnIpcMessagerBind.setOnClickListener(this);
        binding.btnIpcMessager.setOnClickListener(this);
        binding.btnIpcMessager2.setOnClickListener(this);
        binding.btnIpcAidlBind.setOnClickListener(this);
        binding.btnIpcAidlSendmessage.setOnClickListener(this);
        binding.btnIpcAidlGetmessage.setOnClickListener(this);
    }

    private class MessengerHander extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 110:
                    Bundle bundle = msg.getData();
                    String message = bundle.getString("msg");
                    binding.tvMessage.setText(message);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        // Messenager 绑定服务端Service
        if (id == R.id.btn_ipc_messager_bind) {
            Intent intent = new Intent();
            // TODO： 注意包名别搞错了
            intent.setPackage("edu.guigu.serverservice");
            intent.setAction("edu.guigu.serverservice.remote.ACTION_MESSENAGER_SERVICE");
            bindService(intent, messenagerConnection, BIND_AUTO_CREATE);
        }
        // Messenager 向绑定的服务端Service，发送消息
        if (id == R.id.btn_ipc_messager) {
            if (serverMessenager == null) {
                Toast.makeText(this, "请先绑定服务端Service", Toast.LENGTH_SHORT).show();
                return;
            }
            // 通过绑定时得到的服务端Messenager,向服务端发送消息
            // what为1,信息放在bundle中
            try {
                Bundle bundle = new Bundle();
                bundle.putString("msg", "我是来自客户端的消息");
                Message message = Message.obtain();
                message.what = 1;
                message.setData(bundle);
                serverMessenager.send(message);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }
        // Messenager 向绑定的服务端Service，发送消息且将自己（客户端）这边的Messenage传递过去
        if (id == R.id.btn_ipc_messager2){
            if (serverMessenager == null) {
                Toast.makeText(this, "请先绑定服务端Service", Toast.LENGTH_SHORT).show();
                return;
            }
            // 通过绑定时得到的服务端Messenager,向服务端发送消息
            // what为1,信息放在bundle中,
            // 且将本地(客户端)的Messenager放在replayTo中
            try {
                Bundle bundle = new Bundle();
                bundle.putString("msg", "我是来自客户端的消息");
                Message message = Message.obtain();
                message.what = 2;
                message.setData(bundle);
                // TODO : 将本地自己（客户端）这边的Messenage传递过去
                message.replyTo = clientMessenager;
                serverMessenager.send(message);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }
        // AIDL 绑定服务端Service
        if (id == R.id.btn_ipc_aidl_bind) {
            Intent intent = new Intent();
            // TODO： 注意包名别搞错了
            intent.setPackage("edu.guigu.serverservice");
            intent.setAction("edu.guigu.serverservice.remoteaidl.ACTION_AIDLSERVICE");
            bindService(intent, aidlServiceConnection, BIND_AUTO_CREATE);
            return;
        }
        // AIDL 向绑定的服务端Service，发送消息
        if (id == R.id.btn_ipc_aidl_sendmessage) {
            if (iRemoteAidl == null) {
                Toast.makeText(this, "请先绑定服务端Service", Toast.LENGTH_SHORT).show();
                return;
            }
            int type = new Random().nextInt(3) + 1;
            try {
                iRemoteAidl.action(type);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }
        // AIDL 向绑定的服务端Service，获取消息
        if (id == R.id.btn_ipc_aidl_getmessage) {
            if (iRemoteAidl == null) {
                Toast.makeText(this, "请先绑定服务端Service", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                int type = new Random().nextInt(3) + 1;
                Student student = iRemoteAidl.getStudent(type);
                // TODO： 测试,放到UI上展示
                binding.tvMessage.setText(student.getName() + " - " + student.getGrade());
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private Messenger serverMessenager;
    private ServiceConnection messenagerConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("TAG", getClass().getSimpleName() + " onServiceConnected: ");
            // 获得远程服务端的Messenger（里面就已有服务端的Binder）
            serverMessenager = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("TAG", getClass().getSimpleName() + " onServiceDisconnected: ");
        }
    };

    private IRemoteAidl iRemoteAidl;
    private ServiceConnection aidlServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("TAG", getClass().getSimpleName() + " onServiceConnected: ");
            iRemoteAidl = IRemoteAidl.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("TAG", getClass().getSimpleName() + " onServiceDisconnected: ");
        }
    };
}